<?php
            
use app\model\Record; 
use app\model\Util; 
use app\model\Theme; 
use app\model\Worker; 


header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');
//允许跨域
/**
 * Desc:
 * Time: 2021/3/29 5:12 下午
 */
class Flag_Page extends PluginWebPage {
    function main(){
        $method = 'flag_main';
        global $_G,$_P,$_S,$_C;
        $system = $_S;
        $config = $_C;
        $themeid = intval($_P['themeid']);
        if($themeid <= 0){
            $themeid = Theme::getDefaultThemenew();
        }
        $themelist = Theme::getAllTheme();
        $theme = Theme::getThemeById($themeid);
        $end_time = $theme['endtime'];
        $status = isset($_P['status'])?$_P['status']:0;
        $p_id = isset($_P['p_id'])?$_P['p_id']:0;
        $uid = isset($_P['uid'])?intval($_P['uid']):0;
        $page_index = max(1,intval($_P['page']));
        $page_size = 50;
        $page_start = ($page_index-1)*$page_size;
        $type_arr = LotteryModel::getFlagTypeCount($themeid);

        $page_total = LotteryModel::getDefaultLtList($themeid,$status,$p_id,0,0,$uid,true,true);
        $list = LotteryModel::getDefaultLtList($themeid,$status,$p_id,$page_start,$page_size,$uid,true);

        $prize_arr = LotteryModel::getPrizeFlagCount($themeid);
        $can_edit_list = LotteryModel::getCanEditList($themeid);
        $total_show_pr = LotteryModel::getTotalShowPr($themeid);
        foreach ($list as $key => $row){
            if ($row['from_type']=='red_envelope'){
                $item = LotteryModel::getRpFlagItem(['themeid'=>$themeid,'f_id'=>$row['f_id']]);
                if ($item && $row['red_envelopes_amount_min']!=$row['red_envelopes_amount_max']){
                    $list[$key]['title'] = '现金红包'.$item['amount'].'元';
                }
            }
            if(!empty($row['workerid'])){
                $r = Worker::getWokerName($_S,$themeid,$row['workerid']);
                $list[$key]['workername']=$r['workername'];
                $list[$key]['teamname']=$r['teamname'];
                $list[$key]['companyname']=$r['companyname'];
            }
            if ($row['status']==-1){
                $list[$key]['nickname']=$row['xn_nickname'];
                $list[$key]['username']=$row['xn_username'];
                $list[$key]['mobile']=$row['xn_mobile'];
                $list[$key]['avatar']=$row['xn_avatar'];
            }
        }


        $total = $page_total;
        extract(Record::getSearchTime());
        $pager = pagination($page_total,$page_index,$page_size);
        $return_clicent = get_defined_vars();
return $this->view('/lottery/flag/main', $return_clicent);
    }

    function search()
    {
        $method = 'flag_main';
        global $_G,$_P,$_S,$_C;
        $system = $_S;
        $config = $_C;
        $themeid = intval($_P['themeid']);
        if($themeid <= 0){
            $themeid = Theme::getDefaultThemenew();
        }
        $themelist = Theme::getAllTheme();
        $status = $_P['status'];
        $page_index = max(1,intval($_P['page']));
        $page_size = 50;
        $page_start = ($page_index-1)*$page_size;

        if (empty($_P['createtime']['start'])){
            $starttime =db_fetchcolumn ( 'SELECT min(addtime) FROM ' . tablename ( t_fans ) );
            $start_day =  date('Y-m-d',$starttime);
        }else{
            $start_day = $_P['createtime']['start'];
        }
        $end_day = empty($_P['createtime']['end']) ? time(): $_P['createtime']['end'] ;
        $search_data = isset($_P['search_data'])?$_P['search_data']:'';
        if ($search_data){
            $search_data = '%'.$search_data.'%';
        }
        extract(Record::getSearchTime());
        $total = LotteryModel::searchDefaultLt($themeid,$search_data,0,0,$start_day,$end_day,false,true);
        $group_lists = LotteryModel::searchDefaultLt($themeid,$search_data,0,0,$start_day,$end_day,true);
        $can_edit_list = LotteryModel::getCanEditList($themeid);


        if(checksubmit('export_submit', true)){
            $count = $total;
            $page_limit = 2000;
            $pagesize = ceil($count/$page_limit);
            $header = array(
                'uid' => 'UID','nickname' => '昵称', 'username' => '姓名', 'mobile' => '电话',
                'title'=>'奖品名称', 'pay_status' => '定单状态','status' => '状态',
                'created_at'=>'中奖时间','workerid'=>'核销人','checked_at'=>'核销时间'
            );
            $keys = array_keys($header);
            $html = "\xEF\xBB\xBF";
            foreach ($header as $li) {
                $html .= $li . "\t ,";
            }
            $html .= "\n";
                $condition=" WHERE a.themeid=$themeid ";
                if ($status){
                    if ($status!=-1){
                        $condition .= " and a.status=".$status;
                    }else{
                        $condition .= " and a.status > -1";
                    }
                }else{
                    $condition .= " and a.status > -1";
                }
                if ($search_data){
                    $condition .= " AND b.nickname LIKE '".$search_data."'"." or b.mobile LIKE '".$search_data."' "." or a.username LIKE '".$search_data."' ";
                }
                if ($start_day && $end_day && $start_day!=$end_day){
                    $condition .= "  and a.created_at between '".$start_day."' and '".$end_day."'";
                }

                $ex_page = $_P['ex_page']?$_P['ex_page']:1;

                $sql = " SELECT a.*,b.avatar,b.nickname,b.username,b.mobile,c.name,c.title,c.small_img,c.default_type,d.status as pay_status FROM ".tablename(yx_lt_flag)." AS  a ".
                    " LEFT JOIN ".tablename(t_fans)." AS b ON a.uid=b.uid and b.themeid=$themeid".
                    " LEFT JOIN ".tablename(yx_lt_prize)." AS c ON a.p_id=c.p_id and c.themeid=$themeid".
                    " LEFT JOIN ".tablename(t_record)." AS d ON a.uid=d.uid and d.themeid=$themeid".$condition.
                    "  order by a.uid desc limit ". ($ex_page - 1) * $page_limit . ",$page_limit ";

                $list = db_select($sql);

                if (!empty($list)) {
                    $size = ceil(count($list) / 500);
                    for ($i = 0; $i < $size; $i++) {
                        $buffer = array_slice($list, $i * 500, 500);
                        foreach ($buffer as $row) {
//                            if ($row['default_type']!=2){
                                switch ($row['status']){
                                    case 1:
                                        $row['status'] = '待领取';
                                        break;
                                    case 2:
                                        $row['status'] = '已兑换其他当前失效';
                                        break;
                                    case 3:
                                        $row['status'] = '待核销';
                                        break;
                                    case 4:
                                        $row['status'] = '已核销';
                                        break;
                                    default:
                                        $row['status'] = '虚拟数据无需操作';
                                        break;
                                }
                                if ($row['pay_status'] && ($row['pay_status']==1 || $row['pay_status']==3)){
                                    if ($row['pay_status']==1){
                                        $row['pay_status'] = '已支付';
                                    }else{
                                        $row['pay_status'] = '线下订单';
                                    }
                                }else{
                                    $row['pay_status'] = '未支付';
                                }
//                            }
                            $workername = '';
                            if ($row['workerid']){
                                $r = Worker::getWokerName($_S,$themeid,$row['workerid']);
                                $workername=$r['workername']==1?'后台管理员':$r['workername'];
                            }
                            $row['workerid'] = $workername;
                            if ($row['status']!='已核销'){
                                $row['checked_at']='';
                            }
                            if ($row['nickname']){
                                $row['nickname'] = str_replace(',','',$row['nickname']);
                                $row['nickname'] = str_replace('"','',$row['nickname']);
                            }

                            foreach ($keys as $key) {
//                                if ($row['default_type']!=2){
                                    $data[] = $row[$key];
//                                }
                            }
                            if (isset($data)){
                                $user[] = implode("\t ,", $data) . "\t ,";
                                unset($data);
                            }
                        }
                        $html .= implode("\n", $user)."\n";
                        unset($user);
                    }
                }
                $is_end = 0;
                if($ex_page>=$pagesize){
                    $is_end = 1;
                }
                Util::WxJump($_S,$html,'抽奖中奖信息',$themeid,$is_end,$pagesize);
        }

        if (checksubmit('export_fans_submit', true)){
            $count = count($group_lists);
            $page_limit = 2000;
            $pagesize = ceil($count/$page_limit);
            $header = array(
                'uid' => 'UID', 'nickname' => '昵称','username' => '姓名', 'mobile' => '电话',
                'has_order' => '定单状态','jihui'=>'机会剩余','used'=>'机会使用','first_time'=>'第一次抽奖时间', 'teamname'=>'团队', 'workername' => '员工'
            );
            if ($system['softstyle']>10){
                $header['companyname'] = '公司';
            }
            $keys = array_keys($header);
            $html = "\xEF\xBB\xBF";
            foreach ($header as $li) {
                $html .= $li . "\t ,";
            }
            $html .= "\n";
//            for ($j = 1; $j <= $pagesize; $j++) {
                $condition=" WHERE a.themeid=$themeid and b.mobile!='' ";
                if ($status!=0){
                    if ($status!=-1){
                        $condition .= " and a.status=".$status;
                    }else{
                        $condition .= " and a.status > -1";
                    }
                }
                if ($search_data){
                    $condition .= " AND b.nickname LIKE '".$search_data."'"." or b.mobile LIKE '".$search_data."' "." or a.username LIKE '".$search_data."' ";
                }
                if ($start_day && $end_day && $start_day!=$end_day){
                    $condition .= "  and a.created_at between '".$start_day."' and '".$end_day."'";
                }

                $ex_page = $_P['ex_page']?$_P['ex_page']:1;
                $sql = " SELECT a.*,b.avatar,b.nickname,b.username,b.mobile,b.workerid,b.jihui FROM ".tablename(yx_lt_flag)." AS  a ".
                    " LEFT JOIN ".tablename(t_fans)." AS b ON a.uid=b.uid and b.themeid=$themeid".$condition.
                    " group by a.uid order by a.uid desc limit ". ($ex_page - 1) * $page_limit . ",$page_limit ";

                $list = db_select($sql);


                foreach ($list as $kk =>$vv){
                    $fans = LotteryModel::getUserInfoById($vv['uid'],$themeid);
                    //使用抽奖次数
                    $used_flag  = LotteryModel::getUserChanceUsed($themeid,$vv['uid']);
                    $list[$kk]['used'] = $used_flag;
                    //第一次抽奖时间
                    $first_chance = LotteryModel::getUserFirstChanceByWhere($themeid,$vv['uid']);
                    $list[$kk]['first_time'] = $first_chance['created_at'];

                    $themyrecord = Record::getRecordByUid($vv['uid'],$themeid);
                    if ($themyrecord){
                        $list[$kk]['has_order']='已支付';
                    }else{
                        $list[$kk]['has_order']='未支付';
                    }
                    if(!empty($vv['workerid'])){
                        $r = Worker::getWokerName($system,$themeid,$vv['workerid']);
                        $list[$kk]['workername']=$r['workername'];
                        $list[$kk]['teamname']=$r['teamname'];

                        $list[$kk]['companyname']=$r['companyname'];
                    }
                }

                if (!empty($list)) {
                    foreach ($list as $row) {
                        if ($row['nickname']){
                            $row['nickname'] = str_replace(',','',$row['nickname']);
                            $row['nickname'] = str_replace('"','',$row['nickname']);
                        }
                        foreach ($keys as $key) {
                            $data[] = $row[$key];
                        }
                        if (isset($data)){
                            $user[] = implode("\t ,", $data) . "\t ,";
                            unset($data);
                        }
                    }
                    $html .= implode("\n", $user)."\n";
                    unset($user);
//                }
//                if (!empty($list)) {
//                    $size = ceil(count($list) / 500);
//                    for ($i = 0; $i < $size; $i++) {
//                        $buffer = array_slice($list, $i * 500, 500);
//                        foreach ($buffer as $row) {
//                            if ($row['nickname']){
//                                $row['nickname'] = str_replace(',','',$row['nickname']);
//                                $row['nickname'] = str_replace('"','',$row['nickname']);
//                            }
//                            foreach ($keys as $key) {
//                                $data[] = $row[$key];
//                            }
//                            if (isset($data)){
//                                $user[] = implode("\t ,", $data) . "\t ,";
//                                unset($data);
//                            }
//                        }
//                        $html .= implode("\n", $user)."\n";
//                        unset($user);
//                    }
//                }
            }
            //新版本导出合并
            $is_end = 0;
            if($ex_page>=$pagesize){
                $is_end = 1;
            }
            Util::WxJump($_S,$html,'抽奖客资信息',$themeid,$is_end,$pagesize);
        }

        $list = LotteryModel::searchDefaultLt($themeid,$search_data,$page_start,$page_size,$start_day,$end_day);
        $can_del_ids = '';
        foreach ($list as $key => $row){
            if ($row['from_type']=='red_envelope'){
                $item = LotteryModel::getRpFlagItem(['themeid'=>$themeid,'f_id'=>$row['f_id']]);
                if ($item && $row['red_envelopes_amount_min']!=$row['red_envelopes_amount_max']){
                    $list[$key]['title'] = '现金红包'.$item['amount'].'元';
                }
            }
            if(!empty($row['workerid'])){
                $r = Worker::getWokerName($_S,$themeid,$row['workerid']);
                $list[$key]['workername']=$r['workername'];
                $list[$key]['teamname']=$r['teamname'];
                $list[$key]['companyname']=$r['companyname'];
            }
            if ($row['status']==-1){
                $list[$key]['nickname']=$row['xn_nickname'];
                $list[$key]['username']=$row['xn_username'];
                $list[$key]['mobile']=$row['xn_mobile'];
                $list[$key]['avatar']=$row['xn_avatar'];
                $can_del_ids .= $row['f_id'].",";
            }
        }
        if ($can_del_ids){
            $can_del_ids = rtrim($can_del_ids,",");
        }
        $page_total = $total;

        $pager = pagination($page_total,$page_index,$page_size);
        $return_clicent = get_defined_vars();
return $this->view('/lottery/flag/main', $return_clicent);
    }

    //核销奖品
    function convert()
    {
        global $_G,$_P,$_S,$_C;
        $system = $_S;
        $config = $_C;
        $themeid = intval($_P['themeid']);
        if($themeid <= 0){
            $themeid = Theme::getDefaultThemenew();
        }
        $theme = Theme::getThemeById($themeid);
        $f_id = $_P['f_id'];
        $p_id = $_P['p_id'];
        $uid = $_P['uid'];
        $workerid = $_G['user']['uid'];
//        $where = ['f_id'=>$f_id,'themeid'=>$themeid,'uid'=>$uid,'status'=>3];
//        $data = ['status'=>4,'workerid'=>$workerid];
//        $res = LotteryModel::editLtFlagItem($where,$data);
        $res = LotteryModel::editLtFlagItemByWhere($f_id,$themeid,$uid,$workerid);
        if (!$config['yx_lt_convert_only'] && $res){
            //修改其他的奖项为失效
            LotteryModel::editUserLtFlagLose($uid,$themeid,$p_id,$f_id);
        }
        if (empty($res)){
            show_json(1, ['msg'=>'该奖品未兑换或已核销，请检查后重试']);
        }else{
            show_json(0, ['msg'=>'核销成功']);
        }
    }

    function virtual()
    {
        global $_G,$_P,$_S,$_C;
        $system = $_S;
        $config = $_C;
        $themeid = intval($_P['themeid']);
        if($themeid <= 0){
            $themeid = Theme::getDefaultThemenew();
        }
        $total_show_pr = LotteryModel::getTotalShowPr($themeid);
        if ($total_show_pr<=0){
            show_json(0, ['msg'=>'虚拟奖品的中奖记录占比为0，请到奖项列表中修改']);
        }
        $virtual_pids = isset($_P['virtual_pids'])?$_P['virtual_pids']:[];
        $virtual_num = isset($_P['virtual_num'])?$_P['virtual_num']:0;
        $virtualtime = $_P['virtualtime'];
        $start_time = $virtualtime['start'];
        $end_time = $virtualtime['end'];
        if (!$virtual_pids){
            show_json(0, ['msg'=>'虚拟奖品为空']);
        }
        if (!$virtual_num){
            show_json(0, ['msg'=>'虚拟奖品数量为空']);
        }
        if ($end_time<$start_time){
            show_json(0, ['msg'=>'虚拟中奖时间不合法']);
        }
//        if ($end_time>date("Y-m-d H:i:s",time())){
//            $end_time = date("Y-m-d H:i:s",time());
//        }
        $new_pids = '(';
        if ($virtual_pids[0]==0){
            $prize_arr = LotteryModel::getPrizeFlagCount($themeid);
            foreach ($prize_arr as $k => $v){
                if ($v['p_id']!=0){
                    $new_pids .= $v['p_id'].',';
                }
            }
        }else{
            foreach ($virtual_pids as $k => $v){
                if ($v!=0){
                    $new_pids .= $v.',';
                }
            }
        }
        $new_pids = rtrim($new_pids,',').')';
        $res = LotteryModel::getVirtualUserInfo('',$virtual_num,$config,$themeid,$new_pids,$start_time,$end_time);
        if ($res){
            show_json(1, ['msg'=>'操作成功']);
        }else{
            show_json(0, ['msg'=>'操作失败']);
        }
    }

    function del()
    {
        global $_G,$_P,$_S,$_C;
        $system = $_S;
        $config = $_C;
        $themeid = intval($_P['themeid']);
        if($themeid <= 0){
            $themeid = Theme::getDefaultThemenew();
        }
        $theme = Theme::getThemeById($themeid);
        $f_id = isset($_P['f_id'])?$_P['f_id']:0;
        $type = isset($_P['type'])?$_P['type']:'del';
        $del_start = isset($_P['del_start'])?$_P['del_start']:'';
        $del_end = isset($_P['del_end'])?$_P['del_end']:'';
        $del_end = isset($_P['del_end'])?$_P['del_end']:'';
        $del_search = isset($_P['del_search'])?$_P['del_search']:'';

        if ($f_id && $type=='del'){
            $res = db_delete(yx_lt_flag,['f_id'=>$f_id,'themeid'=>$themeid]);
            if (empty($res)){
                show_json(1, ['msg'=>'操作失败，请检查后重试']);
            }else{
                show_json(0, ['msg'=>'操作成功']);
            }
        }
        if ($del_start && $del_end && $type=='del_time'){
            $del_start = $del_start.":00";
            $del_end = $del_end.":00";
            $condition=" and status = -1";
            $condition .= "  and created_at between '".$del_start."' and '".$del_end."'";
            $sql = " delete from ".tablename(yx_lt_flag).
                " WHERE themeid=$themeid".$condition;
            $res = \think\Db::execute($sql);
            if (empty($res)){
                show_json(1, ['msg'=>'操作失败，请检查后重试']);
            }else{
                show_json(0, ['msg'=>'操作成功']);
            }
        }
        if ($del_search && $type=='del_search'){
            $sql = " delete from ".tablename(yx_lt_flag)." where themeid=$themeid and status=-1 and f_id in (".$del_search." )";
            $res = \think\Db::execute($sql);
            if (empty($res)){
                show_json(1, ['msg'=>'操作失败，请检查后重试']);
            }else{
                show_json(0, ['msg'=>'操作成功']);
            }
        }

    }

    //修改中奖记录
    function edit(){
        global $_G,$_P,$_S,$_C;
        $system = $_S;
        $config = $_C;
        $themeid = intval($_P['themeid']);
        if($themeid <= 0){
            $themeid = Theme::getDefaultThemenew();
        }
        $theme = Theme::getThemeById($themeid);
        $edit_pid = isset($_P['edit_pid'])?$_P['edit_pid']:0;
        $flag_id = isset($_P['flag_id'])?$_P['flag_id']:0;
        if ($themeid && $edit_pid && $flag_id){
            //判断当前要修改的奖品的库存
            $new_prize_item = db_get(yx_lt_prize,['themeid'=>$themeid,'p_id'=>$edit_pid]);
            if ($new_prize_item['qty']<1){
                show_json(1, ['msg'=>'当前替换的奖品'.$new_prize_item['title'].'无库存,替换失败。']);
                return;
            }
            //获取原始中奖记录
            $old_flag_item = LotteryModel::getLtFlagItemByWhere(['themeid'=>$themeid,'f_id'=>$flag_id]);
            $old_prize_id = $old_flag_item['p_id'];
            //判断中奖记录中的奖品id 与替换的奖品的id是否一致
            if ($old_prize_id==$edit_pid){
                show_json(1, ['msg'=>'当前替换的奖品'.$new_prize_item['title'].'与中奖记录奖品相同,替换失败。']);
                return;
            }
            //还原历史商品的库存 +1
            $old_update_lt_item_sql = "update ".tablename(yx_lt_prize)." set qty=qty+1,out_qty=out_qty - 1 where p_id='".$old_prize_id."' and themeid='$themeid'";
            $old_lt_item = db_find($old_update_lt_item_sql);


            $where = ['themeid'=>$themeid,'f_id'=>$flag_id];
            $data = ['p_id'=>$edit_pid];
            $edit_res = LotteryModel::editLtFlagItem($where,$data);
            if (!$edit_res){
                show_json(1, ['msg'=>'操作失败，请检查后重试']);
            }else{
                //减少当前操作的商品的库存 -1
                $update_lt_item_sql = "update ".tablename(yx_lt_prize)." set qty=qty-1,out_qty=out_qty + 1 where p_id='".$edit_pid."' and themeid='$themeid'";
                $lt_item = db_find($update_lt_item_sql);
                show_json(0, ['msg'=>'操作成功']);
            }

        }else{
            show_json(1, ['msg'=>'参数缺失，操作失败，请检查后重试']);
        }
    }
}